import { createRouter, createWebHistory } from "vue-router";

// createRouter 创建路由实例
// 配置history模式
// createWebHashHistory 地址栏不带#号
// createWebHistory
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: "/login", component: () => import("../views/login/Login.vue") },
    {
      path: "/",
      component: () => import("../views/main/Main.vue"),
      redirect: "/main/cart",
      children: [
        {
          path: "/main/home",
          component: () => import("../views/home/Home.vue"),
        },
        {
          path: "/main/product",
          component: () => import("../views/product/ProductDetail.vue"),
        },
        {
          path: "/main/cart",
          component: () => import("../views/cart/Cart.vue"),
        },
        {
          path: '/main/profile',
          component: () => import('@/views/profile/MainLayout.vue'),
          children: [
            {
              path: 'user-center',
              redirect: 'user-center/orders', // 改为相对路径
              children: [
                {
                  path: 'orders',
                  name: '订单管理',
                  component: () => import('@/views/profile/UserCenter/OrderManagement.vue')
                }
              ]
            },
            {
              path: 'account-center',
              redirect: 'account-center/address', // 改为相对路径
              children: [
                { path: 'address', name: '收货地址', component: () => import('@/views/profile/AccountCenter/Address.vue') },
                { path: 'settings', name: '账号设置', component: () => import('@/views/profile/AccountCenter/Setting.vue') },
                { path: 'profile', name: '个人信息', component: () => import('@/views/profile/AccountCenter/Profile.vue') },
                { path: 'ticket-buyer', name: '常用购票人', component: () => import('@/views/profile/AccountCenter/TicketBuyer.vue') }
              ]
            }
          ]
        }
      ],
    },
  ],
});

// vite 中的环境变量  import.meta.env.BASE_URL

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem("isLoggedIn") === "true";

  if (to.meta.requiresAuth && !isLoggedIn) {
    next("/login");
  } else {
    next();
  }
});

export default router;
